//
//  UserViewController.m
//  CheekiOS
//
//  Created by mac on 2017/5/9.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UserViewController.h"
#import "GifloginViewController.h"
//签名Cell
#import "UserSignatureCell.h"
#import "CCHStepSizeSlider.h"
//详情cell
#import "UserdetatilTableViewCell.h"
//修改个人信息
#import "UserEditInfoCollionView.h"
//账户
#import "UserAccountViewController.h"
//收益
#import "UserEarningsController.h"
//身份认证
#import "UserRealNameController.h"
//视频认证
#import "UserRealVideoController.h"
//分享
#import "CustomShareView.h"
#import "WXApi.h"
#import "TencentMessageObject.h"
#import "QQApiInterface.h"
#import "WeiboSDK.h"
//设置
#import "UserSetUpViewController.h"
//新手任务
#import "UserNewtaskController.h"
static CGFloat kHomeImgHeight = 284;

#define NAVBAR_CHANGE_POINT 50

@interface UserViewController ()<UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,CustomShareViewDelegate,WXApiDelegate>{
    int   _isBGImage;//0.上传照片（照片）1：修改背景图  2：修改头像照片
}

@property (nonatomic, strong) UIImageView *headerImage;//头部

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSString *btnTag;//第几附图
@property (nonatomic, strong) UILabel *diamondLab;//钻石

@property (nonatomic, strong) UILabel *nameLab;//名字
@property (nonatomic, strong) UIButton *ageBtn;//年龄
@property (nonatomic, strong) UILabel *constellationLab;//星座
@property (nonatomic, strong) UILabel *IdNumberLab;//ID号
@property (nonatomic, strong) CustomShareView *customShareView;//分享


@end

@implementation UserViewController

-(void)viewWillAppear:(BOOL)animated{

    
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTranslucent:YES];
    self.navigationController.navigationBar.hidden = YES;
    [self setNavgationBarHidden];
    
    [self requestUserInfo];


}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-44) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = RGB(243, 243, 243);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    
    
    
    self.headerImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, -kHomeImgHeight*SCREEN_WIDTH_RATIO47, self.view.frame.size.width, kHomeImgHeight)];
    self.headerImage.contentMode = UIViewContentModeScaleAspectFill;
    self.headerImage.clipsToBounds = YES;
    self.headerImage.userInteractionEnabled = YES;





    UIView *view = [UIView new];
    [self.headerImage addSubview:view];
    view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(self.headerImage);
    }];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(kHomeImgHeight*SCREEN_WIDTH_RATIO47, 0, 0, 0)];
    [self.tableView addSubview:self.headerImage];
    
    UIButton *v= [UIButton new];
    v.backgroundColor = [UIColor clearColor];
    v.frame = CGRectMake(0, 0, KScreenWidth, self.headerImage.height);
    [view addSubview:v];
    [v addTarget:self action:@selector(backgroundImageChange) forControlEvents:UIControlEventTouchUpInside];
    
    

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 64)];
    headerView.backgroundColor = [UIColor clearColor];

    _diamondLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, KScreenWidth, 25)];
    _diamondLab.font = FontP(16);
    _diamondLab.textColor = [UIColor whiteColor];
    _diamondLab.textAlignment = NSTextAlignmentCenter;
    
    [headerView addSubview:_diamondLab];

    UIButton *rightdatabtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightdatabtn setBackgroundImage:[UIImage imageNamed:@"p_center_edit_button"] forState:UIControlStateNormal];
    rightdatabtn.frame = CGRectMake(headerView.right-45, 30, 25, 25);
    [rightdatabtn addTarget:self action:@selector(rightdatabtnClick) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:rightdatabtn];

    [view addSubview:headerView];

  
    _customShareView = [[CustomShareView alloc]init];
    
    _customShareView.delegate = self;
    
    [self.view addSubview:_customShareView];
}


- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if (self.tableView) {
        [self.tableView sendSubviewToBack:self.headerImage];
    }
    
}
#pragma mark ============个人信息请求=============
- (void)requestUserInfo{

    
    
    
    [HcardHttpmanager getPersionalUserInfosuccess:^(id sucess) {
        
        self.infoModel = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];

        [self.headerImage sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(self.infoModel.background)] placeholderImage:[UIImage imageNamed:@"llustration"]];

        _diamondLab.text = [NSString stringWithFormat:@"送出%@钻石",self.infoModel.historyCharm];

               [self.tableView reloadData];

    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark - =============== 修改个人资料 ===============
- (void)rightdatabtnClick{
    
    UserEditInfoCollionView *editVC = [[UserEditInfoCollionView alloc] init];
    
    editVC.infoModel = _infoModel;
    
    [self.navigationController pushViewController:editVC animated:YES];
    
}
#pragma mark - =============== 头部背景修改 ==============
-(void)backgroundImageChange{


    
    UserEditInfoCollionView *editVC = [[UserEditInfoCollionView alloc] init];
    
    editVC.infoModel = _infoModel;
    
    [self.navigationController pushViewController:editVC animated:YES];

}
#pragma mark ===========tableViewdelegate   datasource==================
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return 1;
    }else if(section == 1){
        if ([_infoModel.finish isEqualToString:@"100"]) {
            return 0;
        }else{
            return 1;
        }
    }else if(section == 2){
        return 5;
    }else{
        return 1;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        UserSignatureCell *cell = [UserSignatureCell cellWithTableView:tableView indexPath:indexPath];
        cell.infoModel = self.infoModel;
        
        return cell;
    }else if (indexPath.section == 1){
        static NSString *HySliderCell = @"HySliderCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HySliderCell];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HySliderCell];
            
        }
        for (UIView * subView in cell.subviews){
            if ([subView isKindOfClass:[UIView class]]) {
                [subView removeFromSuperview];
            }
        }
       
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = RGB(234, 234, 234);
        UIView *BackView = [UIView new];
        BackView.frame = CGRectMake(0, 10, KScreenWidth, 50);
        BackView.backgroundColor = [UIColor whiteColor];
        
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 14, 30, 30)];
        imgView.image = [UIImage imageNamed:@"p_center_task_button"];
        [BackView addSubview:imgView];
        
        UILabel *imgLab = [UILabel new];
        imgLab.backgroundColor = ColorI(0xf6f6f6);
        imgLab.frame = CGRectMake(imgView.right+10, 15, 2, cell.height-30);
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imgLab.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight | UIRectCornerTopLeft |UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = imgLab.bounds;
        maskLayer.path = maskPath.CGPath;
        imgLab.layer.mask = maskLayer;
        [BackView addSubview:imgLab];
        
        UILabel *taskLab = [UILabel new];
        taskLab.text = @"新手任务";
        taskLab.font = FontP(15);
        taskLab.frame = CGRectMake(imgLab.right+10, 20, 0, 20);
        [taskLab sizeToFit];
        [BackView addSubview:taskLab];
        
        
        
        
        CCHStepSizeSlider *slider1 = [[CCHStepSizeSlider alloc] initWithFrame:CGRectMake(taskLab.right+10, 5, BackView.width-taskLab.width-imgView.width-imgLab.width-45, BackView.height)];
        
        slider1.minimumValue = 0;
        
        slider1.maximumValue = 1;

        float floatString = [_infoModel.finish floatValue]*0.01;
       
        slider1.value = floatString;
       
        slider1.thumbSize = CGSizeMake(20, 20);
        slider1.sliderOffset = 0;
        
        slider1.thumbImage = [UIImage imageNamed:@"p_center_xsrw_round_button"];
        slider1.continuous = NO;
        slider1.type = CCHStepSizeSliderTypeNormal;
        
        [BackView addSubview:slider1];
        [cell addSubview:BackView];

        
        return cell;
    }else if (indexPath.section == 2){
        UserdetatilTableViewCell *cell = [UserdetatilTableViewCell cellWithTableView:tableView indexPath:indexPath];
        
        
        NSArray *arr = [NSArray new];
        arr = @[@"账户",@"收益",@"实名认证",@"视频认证",@"邀请好友"];
        NSMutableArray *arrImg = [NSMutableArray new];
        
        for (int i = 0 ; i < 5 ; i++) {
            NSString *str = [NSString stringWithFormat:@"p_center_account_button_%d",i];
            [arrImg addObject:str];
        }
        
        cell.nameLab.text = arr[indexPath.row];
        cell.imgView.image = [UIImage imageNamed:arrImg[indexPath.row]];
   
        
        
        return cell;
    }else{
        static NSString *setUpCellIdent = @"setUpCellIdent";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:setUpCellIdent];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:setUpCellIdent];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = RGB(234, 234, 234);
            
            UIView *BackView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, KScreenWidth, 57.5)];
            BackView.backgroundColor = [UIColor whiteColor];
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 19, 20,20)];
            imgView.image = [UIImage imageNamed:@"p_center_set_button"];
            [BackView addSubview:imgView];
            
            UILabel *nameLab = [[UILabel alloc] init];
            nameLab.text = @"设置";
            nameLab.font = FontP(15);
            nameLab.textAlignment = NSTextAlignmentLeft;
            nameLab.frame = CGRectMake(imgView.right+10, 20, 0, 20);
            [nameLab sizeToFit];
            [BackView addSubview:nameLab];
            
            [cell addSubview:BackView];
        }
    
        
        return cell;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 3) {
        return 67.5;
    }else{
        return 60;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        UserEditInfoCollionView *editVC = [[UserEditInfoCollionView alloc] init];
        
        editVC.infoModel = _infoModel;
        
        [self.navigationController pushViewController:editVC animated:YES];
    }else if (indexPath.section == 1){
        UserNewtaskController *newtask = [[UserNewtaskController alloc] init];
        [self.navigationController pushViewController:newtask animated:YES];

    
    }else if (indexPath.section == 2){
        switch (indexPath.row) {
            case 0:
            {
                NSLog(@"账户");
                UserAccountViewController *AccountVC = [[UserAccountViewController alloc] init];
                [self.navigationController pushViewController:AccountVC animated:YES];
                
                
            }
                break;
            case 1:
            {
                NSLog(@"收益");
                UserEarningsController *EarninsVc = [[UserEarningsController alloc] init];
                
                [self.navigationController pushViewController:EarninsVc animated:YES];
                
            }
                break;
            case 2:
            {
                NSLog(@"实名认证");
                UserRealNameController *realVC= [[UserRealNameController alloc] init];
                [self.navigationController pushViewController:realVC animated:YES];
            }
                break;
            case 3:
            {
                NSLog(@"视频认证");

                UserRealVideoController *videoVC = [[UserRealVideoController alloc] init];
                [self.navigationController pushViewController:videoVC animated:YES];
            }
                break;
            case 4:{
                NSLog(@"邀请好友");
                [self shareConnectionAction];
            }
                break;
            default:
                break;
        }
    }
    if (indexPath.section == 3) {
        UserSetUpViewController *vc = [[UserSetUpViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark =============邀请好友分享===========
- (void)shareConnectionAction{
    
    [_customShareView showInView:self.view.window];

    
}
- (void)shareControl:(UIButton *)sender buttonTitle:(NSString *)title{
    [_customShareView hideInView];
    NSLog(@"%ld",(long)sender.tag);
    NSInteger shareType = -2;
    if ( [title isEqualToString:@"微信"]) {
        shareType =UMSocialPlatformType_WechatSession;
    }else if ([title isEqualToString:@"朋友圈"]){
        shareType =UMSocialPlatformType_WechatTimeLine;

    }else if ([title isEqualToString:@"QQ空间"]){
        shareType =UMSocialPlatformType_Qzone;

    }else if ([title isEqualToString:@"QQ"]){
        shareType =UMSocialPlatformType_QQ;

    }else if ([title isEqualToString:@"微博"]){
        shareType =UMSocialPlatformType_Sina;

    }else {
        UIPasteboard *pab = [UIPasteboard generalPasteboard];
        
        NSString *string = HttpUrlStringS(@"fenxiang.html");
        
        [pab setString:string];
        
        if (pab == nil) {
            [SVProgressHUD showWithStatus:@"复制失败"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }else
        {
            [SVProgressHUD showWithStatus:@"复制成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                
            });
        }

    }
    if (shareType == -2) {
        NSLog(@"什么都不做");
    }else{
        [self shareWebPageToPlatformType:shareType];

    }

    

}

- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    NSString* thumbURL =  @"";
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"贴脸儿" descr:@"欢迎使用贴脸儿App" thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = HttpUrlStringS(@"fenxiang.html");
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
                [SVProgressHUD showWithStatus:@"分享成功"];
                
                [_customShareView hideInView];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    
                });

                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
//        [self alertWithError:error];
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    //通过滑动的便宜距离重新给图片设置大小
    CGFloat yOffset = scrollView.contentOffset.y;
    if(yOffset<-kHomeImgHeight*SCREEN_WIDTH_RATIO47){
        
        if (self.headerImage) {
            dispatch_async(dispatch_get_main_queue(), ^{
                CGRect frame = self.headerImage.frame;
                frame.origin.y = yOffset;
                frame.size.height = -yOffset;
                self.headerImage.frame = frame;
            });
            
        }
        
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
